package tree;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description: 94. 二叉树的中序遍历
 * User: Li_yizYa
 * Date: 2025/5/21
 * Time: 11:04
 */
public class Solution2 {
    public static List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ret = new LinkedList<>();
        if (root == null) {
            return ret;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode node = stack.pop();
            ret.add(node.val);
            cur = node.right;
        }

        return ret;
    }
    public static List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> ret = new LinkedList<>();
        if (root == null) {
            return ret;
        }
        traversal(root, ret);
        return ret;
    }
    private static void traversal(TreeNode root, List<Integer> ret) {
        if (root == null) {
            return;
        }
        traversal(root.left, ret);
        ret.add(root.val);
        traversal(root.right, ret);
    }

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        node1.left = null;
        node1.right = node2;
        node2.left = node3;
        node2.right = null;
        node3.left = null;
        node3.right = null;
        List<Integer> ret = inorderTraversal(node1);
        for (int num : ret) {
            System.out.println(num);
        }
    }
}
